﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Primitives;
using OpenIddict.Abstractions;
using System.Security.Claims;

namespace Magic.Oidc.AuthorizatonServer
{
    public class AuthorizationService
    {
        public IDictionary<string, StringValues> ParseOAuthParameters(HttpContext httpContext, List<string>? excluding = null)
        {
            excluding ??= new List<string>();

            var parameters = httpContext.Request.HasFormContentType
                ? httpContext.Request.Form
                    .Where(v => !excluding.Contains(v.Key))
                    .ToDictionary(v => v.Key, v => v.Value)
                : httpContext.Request.Query
                    .Where(v => !excluding.Contains(v.Key))
                    .ToDictionary(v => v.Key, v => v.Value);

            return parameters;
        }

        //构建重定向地址
        public string BuildRedirectUrl(HttpRequest request, IDictionary<string, StringValues> oAuthParameters)
        {
            var url = request.PathBase + request.Path + QueryString.Create(oAuthParameters);
            return url;
        }

        //验证授权状态
        public bool IsAuthenticated(AuthenticateResult authenticateResult, OpenIddictRequest request)
        {
            //拒绝授权
            if (!authenticateResult.Succeeded)
            {
                return false;
            }
            //过期
            if (request.MaxAge.HasValue && authenticateResult.Properties != null)
            {
                var maxAgeSeconds = TimeSpan.FromSeconds(request.MaxAge.Value);

                var expired = !authenticateResult.Properties.IssuedUtc.HasValue ||
                              DateTimeOffset.UtcNow - authenticateResult.Properties.IssuedUtc > maxAgeSeconds;
                if (expired)
                {
                    return false;
                }
            }

            return true;
        }

        //public static List<string> GetDestinations(ClaimsIdentity identity, Claim claim)
        //{
        //    var destinations = new List<string>();

        //    if (claim.Type is OpenIddictConstants.Claims.Name or OpenIddictConstants.Claims.Email)
        //    {
        //        destinations.Add(OpenIddictConstants.Destinations.AccessToken);
        //    }

        //    return destinations;
        //}

        //设置令牌归属
        public static List<string> GetDestinations(ClaimsIdentity identity, Claim claim)
        {
            var destinations = new List<string>();

            if (claim.Type is OpenIddictConstants.Claims.Name or OpenIddictConstants.Claims.Email)
            {
                destinations.Add(OpenIddictConstants.Destinations.AccessToken);

                if (identity.HasScope(OpenIddictConstants.Scopes.OpenId))
                {
                    destinations.Add(OpenIddictConstants.Destinations.IdentityToken);
                }
            }

            return destinations;
        }
    }
}
